package coderead.plugin.ui.settings;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.ui.components.JBTextField;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;


public class SettingsPage implements Configurable {
    private final SettingInfo settings;
    private JPanel mainPanel;
    private JTextField remoteField;

    public SettingsPage() {
        SettingPersistent component = ApplicationManager.getApplication().getComponent(SettingPersistent.class);
        this.settings = component.getState();
    }


    @Override
    public @Nls(capitalization = Nls.Capitalization.Title) String getDisplayName() {
        return "Maven Search";
    }

    @Nullable
    @Override
    public JComponent createComponent() {
        if (this.mainPanel != null) {
            return this.mainPanel;
        }
        this.mainPanel = new JPanel(new FlowLayout(0));
        JLabel titleLabel = new JLabel("remote URL:");
        this.mainPanel.add(titleLabel);
        this.remoteField = new JBTextField(20);
        this.remoteField.setText(this.settings.getRemoteUrl());
        this.mainPanel.add(this.remoteField);
        JButton button = new JButton("default");
        button.addActionListener(e -> {
            this.remoteField.setText(SettingInfo.defaultRemoteUrl);
        });
        this.mainPanel.add(button);
        return this.mainPanel;

    }

    @Override
    public boolean isModified() {
        return isModified(this.remoteField, this.settings.getRemoteUrl());
    }

    @Override
    public void apply() throws ConfigurationException {
        this.settings.setRemoteUrl(this.remoteField.getText());
    }

    @Override
    public void reset() {
        this.remoteField.setText(this.settings.getRemoteUrl());
    }

}
